package arithmetic;

import java.util.LinkedHashMap;

public class ArithmeticModel {

	private Character[] abc = {'e','t','a','o','i','n','s','r','h','d','l','u','c',
								'm','f','y','w','g','p','b','v','k','x','q','j','z','\0'};
	
	private int[] freq = {21912,16587,14810,14003,13318,12666,11450,10977,10795,7874,7253,5246,4943,
							4761,4200,3853,3819,3693,3316,2715,2019,1257,315,205,188,128,1};
	
	private LinkedHashMap <Character, Integer> charCount;
	private LinkedHashMap <Character, Integer> charCumCount;
	private int totalCount = 0;
	private int range;
	private int bitLength;
	
	public ArithmeticModel(){
		charCount = new LinkedHashMap <>();
		charCumCount = new LinkedHashMap <>();
		int i = 0;
		for(char ch : abc){
			charCount.put(ch, freq[i]);
			charCumCount.put(ch, freq[i]+totalCount);
			
			totalCount += freq[i++];
		}
		bitLength = (int) Math.ceil((Math.log10(totalCount*4))/(Math.log10(2)));	//number of bits required
		this.range = (int) Math.pow(2, bitLength);
	}
	
	
	public int getTotalCount(){
		return this.totalCount;
	}
	
	public int getBitLength() {
		return bitLength;
	}


	public int getRange() {
		return range;
	}


	public int getLetterCount(char ch){
		return charCount.get(ch);
	}
	
	public int getLetterCumCount(char ch){
		return charCumCount.get(ch);
	}
	
	public int getPreviousLetterCumCount(char letter){
		return charCumCount.get(letter) - charCount.get(letter);
	}
	
	public char getCharByTag(int tag){
		
		Integer[] arr = charCumCount.values().toArray(new Integer[0]);
		for(int i=0; i < arr.length; i++ ){
			if(tag < arr[i])
				return abc[i];
		}
		return '\0';
	}

}
